package com.geek.novel.services

import com.geek.novel.common.Constant
import com.geek.novel.entity.SysUser
import com.geek.novel.network.RslHandler
import com.geek.novel.network.RepositoryProvider
import com.geek.novel.repository.HttpRepository
import com.geek.novel.utils.AesEncryptUtil

/**
 * 授权相关Service
 */
class AuthService(rslHandler: RslHandler): BaseService(rslHandler) {

    private var repository: HttpRepository = RepositoryProvider.provideRepository()

    /**
     * 登录接口
     */
    fun login(username: String, password: String) {
        //加密算法
        val passwordAES = AesEncryptUtil.encrypt(password)
        //调用登录接口
        val observer = repository.login(username, passwordAES)
        compose(observer, Constant.HTTP_KEY_LOGIN, LoginResult::class.java)
    }

    /**
     * 获取用户信息接口
     */
    fun getUserInfo() {
        val observer = repository.getUserInfo()
        compose(observer, Constant.HTTP_KEY_GET_USERINFO, SysUser::class.java)
    }

    /**
     * 获取用户信息接口
     */
    fun updateUserInfo(user: SysUser) {
        val observer = repository.updateUserInfo(user)
        compose(observer, Constant.HTTP_KEY_UPDATE_USERINFO, SysUser::class.java)
    }

    /**
     * 注册接口
     */
    fun regist(user: SysUser) {
        //加密算法
        user.password = AesEncryptUtil.encrypt(user.password)
        user.passwordAgain = AesEncryptUtil.encrypt(user.passwordAgain)
        val observer = repository.regist(user)
        compose(observer, Constant.HTTP_KEY_REGIST, LoginResult::class.java)
    }

    /**登录接口返回结果*/
    class LoginResult{
        var token: String? = null
    }

    /**
     * 修改密码接口
     */
    fun modifyPassword(user: SysUser, password: String) {
        //加密算法
        val passwordEncrypt = AesEncryptUtil.encrypt(password)
        user.password = AesEncryptUtil.encrypt(user.password)
        user.passwordAgain = AesEncryptUtil.encrypt(user.passwordAgain)
        val observer = repository.modifyPassword(user, passwordEncrypt)
        compose(observer, Constant.HTTP_KEY_MODIFY_PASSWORD, SysUser::class.java)
    }

    /**
     * 发送忘记密码的验证码
     */
    fun sendForgetPassValidateCode(target: String) {
        val observer = repository.sendForgetPassValidateCode(target)
        compose(observer, Constant.HTTP_KEY_FORGET_PASSWORD_VALIDATE_CODE)
    }

    /**
     * 忘记密码-修改密码
     */
    fun forgetPassword(target: String, type: String, code: String, password: String, passwordAgain: String) {
        //加密算法
        val passwordEncrypt = AesEncryptUtil.encrypt(password)
        val passwordAgainEncrypt = AesEncryptUtil.encrypt(passwordAgain)
        val observer = repository.forgetPassword(target, type, code, passwordEncrypt, passwordAgainEncrypt)
        compose(observer, Constant.HTTP_KEY_FORGET_PASSWORD, SysUser::class.java)
    }

}
